const { dictionary_type, dictionary_items } = require("@/model");

class DictionaryService {
  async getCategories(params) {
    const { pageNum = 10, pageIndex = 1, ...rest } = params;
    const categories = await dictionary_type.findAll({
      where: rest,
    });
    return categories?{
      list: categories
    }:null;
  }

  async getAllList() {
    const categoriesWithItems = await dictionary_type.findAll({
      include: [{
        model: dictionary_items,
        as: 'itemsById',
      }]
    });
    return categoriesWithItems;
  }

  async getDictByCode(code) {
    const items = await dictionary_items.findAll({
      where: {
        type_code:code
      }
    });
    return {
      list : items || []
    }
  }

  async getCategoryById(id) {
    const category = await dictionary_type.findByPk(id);
    if (!category) throw new Error('分类不存在');
    return category;
  }

  async saveCategory(data) {
    const [category] = await dictionary_type.upsert(data); // 创建或更新分类
    return category;
  }

  async deleteCategory(id) {
    const rows = await dictionary_type.destroy({ where: { id } });
    if (rows === 0) throw new Error('删除失败或分类不存在');
    return true;
  }


  async saveItem(data) {
    // 如果有type_code但没有type_id，自动补全type_id
    if (data.type_code && !data.type_id) {
      const type = await dictionary_type.findOne({ where: { code: data.type_code } });
      if (!type) throw new Error('type_code无效，未找到对应字典类型');
      data.type_id = type.id;
    }
    // 如果有type_id但没有type_code，自动补全type_code
    if (data.type_id && !data.type_code) {
      const type = await dictionary_type.findByPk(data.type_id);
      if (!type) throw new Error('type_id无效，未找到对应字典类型');
      data.type_code = type.code;
    }
    const [item] = await dictionary_items.upsert(data); // 创建或更新字典项
    return item;
  }

  async deleteItem(id) {
    const rows = await dictionary_items.destroy({ where: { id } });
    if (rows === 0) throw new Error('删除失败或字典项不存在');
    return true;
  }
}

module.exports = new DictionaryService();